<?php

namespace app\api\controller\user;

use app\api\controller\AuthController;
use app\api\service\GoldService;
use app\api\service\IntegralService;
use app\api\service\UserService;

class GoldController extends AuthController
{
    /**
     * 兑换金豆
     * */
    public function redeem()
    {
        $param = $this->request->param();

        if (empty($param['store_id']) || empty($param['gold_num'])){
            return json(['code' =>0, 'msg' => '参数非法!']);
        }

        $gold_scale = IntegralService::getGoldRedeemScale($param['store_id']);

        $user_id = $this->request->user['user_id'];

        $user_integral = IntegralService::getUserIntegral($user_id);

        $need_integral = (int)$param['gold_num']*(int)$gold_scale;

        if ($need_integral>$user_integral){
            return json(['code' =>0, 'msg' => '积分不足,兑换失败!']);
        }

        $data = [
            'user_id' => $user_id,
            'change_integral' => $need_integral,
            'gold_num' => $param['gold_num']
        ];

        $result =  GoldService::reedGold($data);

        return  $result ? json(['code' =>1, 'msg' => '兑换成功!']) : json(['code' =>0, 'msg' => '兑换失败!']);


    }
}